// Connect.cpp : Implementation of CConnect
#include "stdafx.h"
#include "AddIn.h"
#include "Connect.h"
#include <atlstr.h>

extern CAddInModule _AtlModule;

// When run, the Add-in wizard prepared the registry for the Add-in.
// At a later time, if the Add-in becomes unavailable for reasons such as:
//   1) You moved this project to a computer other than which is was originally created on.
//   2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
//   3) Registry corruption.
// you will need to re-register the Add-in by building the PageRemeberAddinSetup project, 
// right click the project in the Solution Explorer, then choose install.


// CConnect
STDMETHODIMP CConnect::OnConnection(IDispatch *pApplication, AddInDesignerObjects::ext_ConnectMode /*ConnectMode*/, IDispatch *pAddInInst, SAFEARRAY ** /*custom*/ )
{
	pApplication->QueryInterface(__uuidof(IDispatch), (LPVOID*)&m_pApplication);
	pAddInInst->QueryInterface(__uuidof(IDispatch), (LPVOID*)&m_pAddInInstance);
	DispEventAdvise(m_pApplication);
	m_rememberSettings.Load();
	return S_OK;
}

STDMETHODIMP CConnect::OnDisconnection(AddInDesignerObjects::ext_DisconnectMode /*RemoveMode*/, SAFEARRAY ** /*custom*/ )
{
	DispEventUnadvise(m_pApplication);
	m_pApplication = NULL;
	m_pAddInInstance = NULL;
	m_rememberSettings.Save();
	return S_OK;
}

STDMETHODIMP CConnect::OnAddInsUpdate (SAFEARRAY ** /*custom*/ )
{
	return S_OK;
}

STDMETHODIMP CConnect::OnStartupComplete (SAFEARRAY ** /*custom*/ )
{
	return S_OK;
}

STDMETHODIMP CConnect::OnBeginShutdown (SAFEARRAY ** /*custom*/ )
{
	return S_OK;
}

void CConnect::DocumentOpen(IDispatchPtr ptr)
{
	CComQIPtr<_Document> spDoc(ptr);
	ATLASSERT(spDoc);

	CString strPath = GetFullPath(spDoc);

	long lScrollPercentage = m_rememberSettings.GetScrollPercentage(strPath);
	spDoc->ActiveWindow->ActivePane->VerticalPercentScrolled = 100;//scroll to the end first, because Documnt Open event fires before all pages loaded.
	spDoc->ActiveWindow->ActivePane->VerticalPercentScrolled = lScrollPercentage;
	/*CString strFormattedMessage;
	strFormattedMessage.Format(_T("Path = %s"), strPath);*/
}

void CConnect::DocumentBeforeClose(IDispatchPtr ptr, VARIANT_BOOL* cancel)
{
	CComQIPtr<_Document> spDoc(ptr);
	ATLASSERT(spDoc);
	CString strFullPath = GetFullPath(spDoc);
	/*CString strFormattedMessage;	
	strFormattedMessage.Format(_T("Path = %s, Pages->Count = %ld, VerticalPercentScrolled = %ld"), strPath, spDoc->ActiveWindow->ActivePane->Pages->Count, spDoc->ActiveWindow->ActivePane->VerticalPercentScrolled);*/
	m_rememberSettings.Add(strFullPath, spDoc->ActiveWindow->ActivePane->VerticalPercentScrolled);
}

CString CConnect::GetFullPath(CComQIPtr<_Document>& spDoc)
{
	CString strName = spDoc->Name;
	CString strPath = spDoc->Path;
	CString strFullPath;
	strFullPath.Format(_T("%s\\%s"), strPath, strName);
	return strFullPath;
}
